# -*- coding: utf-8 -*-
# Project : flacon
# File : disc.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.


from settings import *
from flaconglobal import *
from audiofiles import *
from track import *
from trackset import *
import inet

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import *


class Disc(QObject):
   #****************************************************************
   #
   #****************************************************************
    def __init__(self, parent = None):
        QObject.__init__(self)
        self._project = None
        self._trackSets = []
        self._tracks = TrackSet()

        self._audioFile = None
        self._downloader = None


   #****************************************************************
   #
   #****************************************************************
    def addTrackSet(self, trackSets):

        def find(tsList, uri):
            for ts in tsList:
                if ts.uri() == uri:
                    return ts
            return None

        if isinstance(trackSets, TrackSet):
            trackSets = [trackSets]

        # Remove old doublicates ..........................
        for t in trackSets:
            t2 = find(self._trackSets, t.uri())
            if t2:
                self._trackSets.remove(t2)

        # Add new .........................................
        for t in trackSets:
            self._trackSets.append(t)
            t.setDisc(self)


   #****************************************************************
   #
   #****************************************************************
    def trackSets(self):
        return self._trackSets


   #****************************************************************
   # trackSet can be integer or TrackSet
   #****************************************************************
    def selectTrackSet(self, trackSet):
        if isinstance(trackSet, TrackSet):
            trackSet = self._trackSets.index(trackSet)

        self._tracks =  self._trackSets[trackSet]
        if self._project:
            self._project.layoutChanged()


   #****************************************************************
   #
   #****************************************************************
    def canDownloadInfo(self):
        return inet.FreeDbDowloader.canDownload(self)


   #****************************************************************
   #
   #****************************************************************
    def downloadInfo(self):
        self._downloader = inet.FreeDbDowloader(self)
        self.connect(self._downloader, SIGNAL('done()'), self._downloadFinished)
        self._downloader.get()
        self.emit(SIGNAL("downloadStarted()"))


   #****************************************************************
   #
   #****************************************************************
    def _downloadFinished(self):
        def cleanString(s):
            return s.toUpper().replace(QRegExp("(^|\s)THE "), '').replace(QRegExp("[\s\.,_/\\\%\#\@\&\^\d]"), "")

        res = self._downloader.result()
        if not len(res):
            self.emit(SIGNAL("downloadFinished()"))
            return

        self.addTrackSet(res)

        artist = cleanString(self._tracks[0].artist()) if self._tracks.count() else QString()

        active = res[0]
        for trackSet in res:
            if artist == cleanString(trackSet[0].artist()):
                active = trackSet
                break

        self._tracks = active

        if self._project:
            self._project.layoutChanged()

        self.emit(SIGNAL("downloadFinished()"))


   #****************************************************************
   #
   #****************************************************************
    def project(self):
        return self._project


   #****************************************************************
   #
   #****************************************************************
    def setProject(self, value):
        self._project = value


   #****************************************************************
   #
   #****************************************************************
    def trackDataChanged(self, trackNum):
        if self._project:
            self._project.trackDataChanged(self, trackNum)


   #****************************************************************
   #
   #****************************************************************
    def tracks(self):
        return self._tracks


   #****************************************************************
   #
   #****************************************************************
    def cueTracks(self):
        for ts in self._trackSets:
            if isinstance(ts, CueTrackSet):
                return ts


   #****************************************************************
   #
   #****************************************************************
    def audioFile(self):
        return self._audioFile


   #****************************************************************
   #
   #****************************************************************
    def setAudioFile(self, audioFile):
        self._audioFile = audioFile


   #****************************************************************
   #
   #****************************************************************
    def cueFileName(self):
        for tracks in self._trackSets:
            if isinstance(tracks, CueTrackSet):
               return tracks.uri()

        return QString()


   #****************************************************************
   #
   #****************************************************************
    def audioFileName(self):
        if self._audioFile:
            return self._audioFile.fileName()

        return QString()


   #****************************************************************
   #
   #****************************************************************
    def canConvert(self):
        return (self._audioFile and
                self._tracks.count()
               )


   #****************************************************************
   #
   #****************************************************************
    def canConvertString(self, divider = '\n'):
        msg = QStringList()

        if not self._audioFile:
            msg << self.tr("Audio file not set.")

        if not self._tracks.count():
            msg << self.tr("CUE file not set.")

        return msg.join(divider)


   #****************************************************************
   #
   #****************************************************************
    def cueData(self):
        for ts in self._trackSets:
            if isinstance(ts, CueTrackSet):
                return ts.cueData()

        return None